package dao.recording.imp;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import pojo.Book;
import pojo.Recording;
import util.DBUtil;
import dao.recording.RecordingDao;

public class RecordingDaoImp implements RecordingDao {

	@Override
	public int addRecording(Recording recording) {
		String sql = "insert into recording(id,user_id,book_id,order_time) values (?,?,?,?)";
		Connection con =null;
		PreparedStatement pst = null;
		int m = 0;
		try {
			con = DBUtil.createConnection();
			pst=con.prepareStatement(sql);
			pst.setString(1, recording.getId());
			pst.setString(2, recording.getUserId());
			pst.setString(3, recording.getBookId());
			pst.setDate(4, new java.sql.Date(recording.getOrderTime().getTime()));
			m = pst.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			DBUtil.close(con,pst,null);
		}
		
		System.out.println(m);
		return m;
	}

	@Override
	public List<Recording> findAll() {
		// TODO Auto-generated method stub
		String sql = "select id,user_id,book_id,order_time from recording";
		PreparedStatement pst = null;
		ResultSet rs = null;
		List<Recording> list = new ArrayList<Recording>();
		Connection con =null;
		Recording recording;
		try {
		    con = DBUtil.createConnection();
			pst=con.prepareStatement(sql);
			rs = pst.executeQuery();
			while(rs.next()){
				String uid = rs.getString("user_id");
				String bid = rs.getString("book_id");
				String id = rs.getString("id").trim();
				Date time = rs.getDate("order_time");
				recording = new Recording(id, uid, bid, time);
				list.add(recording);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			DBUtil.close(con,pst,rs);
		}
		return list;
	}

}
